package cn.edu.swu.miniwebsvr.core;

import cn.edu.swu.miniwebsvr.handler.DefaultHandler;
import java.io.OutputStream;
import java.io.IOException;

public class Router {

    public void route(Parameter request, OutputStream response) {
        Config config = Config.getInstance();

        // TODO: [222024321072047/李明燊] 根据请求的URL获取Handler
        Handler handler = config.getHandler(request.getUrl());

        if (handler == null) {
            // 如果没有匹配的路由，使用 DefaultHandler 处理
            System.err.println("未找到匹配的处理器，URL: " + request.getUrl());
            handler = config.getHandler("/");
        }

        if (handler != null) {
            try {
                System.out.println("路由请求到处理器: " + handler.getClass().getSimpleName() + " - URL: " + request.getUrl());
                handler.handle(request, response);
            } catch (Exception e) {
                System.err.println("处理器执行异常: " + e.getMessage());
                e.printStackTrace();
                sendErrorResponse(500, "Internal Server Error - Handler Execution Failed", response);
            }
        } else {
            // TODO: [222024321072047/李明燊] 如果连DefaultHandler都没有，返回500 Internal Server Error
            System.err.println("严重错误：连默认处理器都不存在！");
            sendErrorResponse(500, "Internal Server Error - No Handler Available", response);
        }
    }

    /**
     * 发送HTTP错误响应
     * @param statusCode HTTP状态码
     * @param statusMessage 状态描述
     * @param response 输出流
     */
    private void sendErrorResponse(int statusCode, String statusMessage, OutputStream response) {
        try {
            String htmlContent = "<!DOCTYPE html>" +
                    "<html>" +
                    "<head>" +
                    "<title>" + statusCode + " " + statusMessage + "</title>" +
                    "<style>" +
                    "body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }" +
                    "h1 { color: #d32f2f; }" +
                    ".container { max-width: 500px; margin: 0 auto; }" +
                    "</style>" +
                    "</head>" +
                    "<body>" +
                    "<div class='container'>" +
                    "<h1>" + statusCode + " - " + statusMessage + "</h1>" +
                    "<p>抱歉，服务器在处理您的请求时遇到了问题。</p>" +
                    "<p>请稍后重试或联系管理员。</p>" +
                    "<hr>" +
                    "<p><small>MiniWebSvr - 222024321072047/李明燊</small></p>" +
                    "</div>" +
                    "</body>" +
                    "</html>";

            String httpResponse = "HTTP/1.1 " + statusCode + " " + statusMessage + "\r\n" +
                    "Content-Type: text/html; charset=utf-8\r\n" +
                    "Content-Length: " + htmlContent.getBytes("UTF-8").length + "\r\n" +
                    "Connection: close\r\n" +
                    "\r\n" +
                    htmlContent;

            response.write(httpResponse.getBytes("UTF-8"));
            response.flush();
        } catch (IOException e) {
            System.err.println("发送错误响应时发生异常: " + e.getMessage());
        }
    }

    /**
     * 发送404 Not Found错误响应
     * @param request 请求参数
     * @param response 输出流
     */
    public void sendNotFound(Parameter request, OutputStream response) {
        System.err.println("资源未找到: " + request.getUrl());
        sendErrorResponse(404, "Not Found", response);
    }

    /**
     * 发送405 Method Not Allowed错误响应
     * @param request 请求参数
     * @param response 输出流
     */
    public void sendMethodNotAllowed(Parameter request, OutputStream response) {
        System.err.println("方法不允许: " + request.getMethod() + " " + request.getUrl());
        sendErrorResponse(405, "Method Not Allowed", response);
    }

    /**
     * 发送400 Bad Request错误响应
     * @param request 请求参数
     * @param response 输出流
     * @param message 错误消息
     */
    public void sendBadRequest(Parameter request, OutputStream response, String message) {
        System.err.println("错误请求: " + request.getUrl() + " - " + message);
        sendErrorResponse(400, "Bad Request: " + message, response);
    }
}
